/**
 * Created by no1 on 2015/7/24.
 */

'use strict';

let Base = require('./Base');
let mysqlDao = require('./mysqlDao/OrderDao.js');
let DD = require('./daoLoader');
let F = require('../function');
var util = require("util");

let mysqlUserDao = new DD.mysqlDB.UserDao();
let mysqlOrderDao = new DD.mysqlDB.OrderDao();
let mongoWareDao = new DD.mongoDB.WareDao();

function OrderDispatcher(data) {
  data = data || {};
  data.dao = data.dao || mysqlOrderDao;
  data.esDao = data.esDao || {};
  data.redisDao = data.redisDao || {};
  data.modelName = data.modelName || 'order';
  data.modelType = data.modelType || 'mysql';
  this.data = data;
  Base.call(this, this.data);
}
util.inherits(OrderDispatcher, Base);

let rp = OrderDispatcher.prototype;

//订单编号 150215120555 4855  意思: 15年02月15日12时05分55秒 +4位随机数(第一不为0,唯一)
function genOrderCode() {
  function keeLastTwo(digit) {
    var tmp = digit + '';
    if (tmp.length == 0) tmp = '00';
    else if (tmp.length == 1)tmp = '0' + tmp;
    else if (tmp.length > 2)tmp = tmp.substr(tmp.length - 2, 2);
    return tmp
  }

  var now = new Date();
  var year = now.getFullYear() + '';
  var month = now.getMonth() + 1 + '';
  var day = now.getDate();
  var hour = now.getHours();
  var min = now.getMinutes();
  var sec = now.getSeconds();

  var dateStr = keeLastTwo(year) +
    keeLastTwo(month) +
    keeLastTwo(day) +
    keeLastTwo(hour) +
    keeLastTwo(min) +
    keeLastTwo(sec);
  var rdmA = Math.floor(Math.random() * 9 + 1); //[1~10)
  var rdmB = Math.floor(Math.random() * 1000);// [0~999)
  var rdm = rdmA * 1000 + rdmB;
  return dateStr + rdm;
}

/**
 *@todo 添加订单
 *@param  {Object}  fields  所有参数
 *@param  {number}  pay_way    付款方式  1:到店支付；2支付宝支付；3：微信支付
 */
rp.add = function*(fields) {
  let arr = ['wareid', 'uid', 'price', 'total_price', 'quantity', 'pay_way'], parameters = {};
  for (let one of arr) parameters[one] = fields[one];

  parameters.status = 0;// 0，未确认/代付款；1，已确认 /未消费/可使用
  parameters.consumption_status = 0;//消费状态 0不在状态范围 1未消费 2已消费
  parameters.refund_status = 0;//退款状态 0 没退款 1 有退款
  parameters.payment_status = 0;//支付状态 0 未付款 1已付款
  parameters.evaluation_status = 0;//评价状态 0 不在状态范围 1 未评价 1已评价

  parameters.order_code = genOrderCode();
  if (parameters.quantity < 0) F.returnData(1, '购买数量有误');
  parameters.quantity || (parameters.quantity = 1);
  parameters.date = parseInt(new Date(new Date().format('yyyy-MM-dd hh:mm:ss') + ' CST+800').getTime() / 1000);
  //验证是否有用户
  let retUser = yield mysqlUserDao.findById(parameters.uid);
  if (retUser.error == 1) return F.returnData(1, retUser.msg, retUser.data);

  //检验是否存在商品
  let retWare = yield F.getDataFromDispatcher('wareDispatcher', 'getOneByQuery', {id: parameters.wareid});
  if (retWare.error == 1) return F.returnData(1, retWare.msg, retWare.data);
  parameters.warever = retWare.data.version;
  if (!retWare.data.vendorid) return F.returnData(1, '该商品没有商家id,数据有误');
  parameters.vendorid = retWare.data.vendorid;

  //保存数据
  let ret = yield this.dao.save(parameters);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  ////保存orderPayWay
  //let opyData = {};
  //opyData.pay_way = parameters.pay_way;
  //opyData.order_id = 55;
  //opyData.price = parameters.price;
  //opyData.return_data = parameters.returnData||'支付成功,你的支付宝流水号:fdfsdfsf165456564';
  //opyData.coupon_code = parameters.coupon_code||2;
  ////修改OrderPayWay
  //let retOPW = yield this.OrderPayWayDispatcher.addformOrderDispatcher(opyData);
  //return F.returnData(0, retOPW.msg, retOPW.data);

  //修改商品的销量
  //let retWareBuy = yield mongoWareDao.buyOne(parameters.wareid);//购买数量加一
  let retWareBuy = yield F.getDataFromDispatcher('wareDispatcher', 'buySome', parameters.wareid, parameters.quantity);
  if (retWareBuy.error == 1) return F.returnData(1, retWareBuy.msg, retWareBuy.data);

  //拼接返回数据
  let retData = {};

  //找商家的信息
  let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'getOneByQuery', {id: retWare.data.vendorid});
  if (retVendor.error == 1) return F.returnData(1, retVendor.msg, retVendor.data);

  retData.orderid = ret.data.orderid;
  retData.price = ret.data.price;
  retData.wareName = retWare.data.name;
  retData.vendorName = retVendor.data.name;


  return F.returnData(0, ret.msg, retData);


};

/**
 @todo 更新
 */
rp.update = function*(fields) {

  let opt = {};
  opt.orderid = fields.orderid;

  let parameters = fields.updateInfo;
  delete parameters.wareid;
  if (parameters.pay_way !== undefined && parameters.pay_way != 1) return F.returnData(1, '暂时还没开放其他支付方式');
  //更新订单信息
  let retOrder = yield this.dao.update(parameters, opt);
  if (retOrder.error == 1) return F.returnData(1, retOrder.msg, retOrder.data);


  //修改商品的销量
  let wareName = '';
  if (retOrder.data.wareid != 1) {
    let retWare = yield F.getDataFromDispatcher('wareDispatcher', 'getOneByQuery', {id: retOrder.data.wareid});
    if (retWare.error == 1) return F.returnData(1, retWare.msg, retWare.data);
    wareName = retWare.data.name;
  }


  //拼接返回的结果
  let retData = {};
  retData.orderid = retOrder.data.orderid;
  retData.wareName = wareName || '社区的商品';

  return F.returnData(0, retOrder.msg, retData);
};

/**
 @todo list
 */
rp.list = function*(fields) {

  let parameters = {}
    , page = fields.page || 1
    , pageSize = fields.pageSize || 50
    , retData = [], wareidList = [], wareList = [], vendorList = [], vendoridList = [],temp;

  fields.uid = fields.uid || 0;
  fields.orderid = fields.orderid || 0;
  fields.order_code = fields.order_code || 0;
  fields.wareid = fields.wareid || 0;
  parameters.status = 1;
  if (fields.status != null) parameters.status = fields.status;

  //按用户uid查询
  if (fields.act == 1) {
    if (!fields.uid) return F.returnData(1, '必须有用户id');
    parameters.uid = fields.uid;

    //获取订单列表
    let retOrder = yield this.dao.getByQuery(parameters, page, pageSize);
    if (retOrder.error == 1) return F.returnData(1, retOrder.msg, retOrder.data);

    for (let one of retOrder.data) {
      wareidList.push(one.wareid || 0);
      vendoridList.push(one.vendorid || 0);
    }

    //找商品的信息
    let retWare = yield F.getDataFromDispatcher('wareDispatcher', 'findByDis', {id: {$in: wareidList}}, {arrDel: ['graphicDetails', 'shops', 'notesToBuy', 'categories']});
    wareList = retWare.data;
    if (retWare.error == 1) wareList = [];
    //找商家的信息
    let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: {$in: vendoridList}});
    vendorList = retVendor.data;
    if (retVendor.error == 1) vendorList = [];

    //拼接返回的结果
    for (let one of retOrder.data) {
      temp = {};
      temp.orderid = one.orderid;
      temp.vendorid = one.vendorid;
      temp.wareid = one.wareid;
      temp.totalPrice = one.total_price;
      temp.quantity = one.quantity;
      temp.price = one.price || 0;
      temp.status = one.status;
      temp.has_consumed_number = one.has_consumed_number;
      temp.refunding_number = one.refunding_number;
      temp.has_refunded_number = one.has_refunded_number;
      temp.daily_thread_id = one.daily_thread_id;
      temp.uid = one.uid;
      temp.date = one.date;
      temp.order_code = one.order_code;
      //找商品的信息
      for (let ware of wareList) {
        if (one.wareid == ware.id) {
          temp.wareName = ware.name;
          temp.image = ware.images[0];
          break;
        }
      }
      for (let vendor of vendorList) {
        if (one.vendorid == vendor.id) {
          temp.vendorName = vendor.name;
          break;
        }
      }
      //添加到返回数据中
      retData.push(temp);
    }
    return F.returnData(0, retOrder.msg, retData);
  }
  //按商家vendorid查询
  else if (fields.act == 2) {
    if (fields.uid > 0) parameters.uid = fields.uid;
    else if (fields.orderid > 0) parameters.orderid = fields.orderid;
    else if (fields.wareid) parameters.wareid = fields.wareid;
    else if (fields.order_code) parameters.order_code = fields.order_code;
    parameters.vendorid = fields.vid;

    //获取订单列表
    let retOrder = yield this.dao.getByQuery(parameters, page, pageSize);
    if (retOrder.error == 1) return F.returnData(1, retOrder.msg, retOrder.data);

    for (let one of retOrder.data) {
      wareidList.push(one.wareid || 0);
      vendoridList.push(one.vendorid || 0);
    }

    //找商品的信息
    let retWare = yield F.getDataFromDispatcher('wareDispatcher', 'findByDis', {id: {$in: wareidList}}, {arrDel: ['graphicDetails', 'shops', 'notesToBuy', 'categories']});
    wareList = retWare.data;
    if (retWare.error == 1) wareList = [];
    //找商家的信息
    let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: {$in: vendoridList}});
    vendorList = retVendor.data;
    if (retVendor.error == 1) vendorList = [];

    //拼接返回的结果
    for (let one of retOrder.data) {
      temp = {};
      temp.orderid = one.orderid;
      temp.vendorid = one.vendorid;
      temp.wareid = one.wareid;
      temp.totalPrice = one.total_price;
      temp.quantity = one.quantity;
      temp.price = one.price || 0;
      temp.status = one.status;
      temp.has_consumed_number = one.has_consumed_number;
      temp.refunding_number = one.refunding_number;
      temp.has_refunded_number = one.has_refunded_number;
      temp.daily_thread_id = one.daily_thread_id;
      temp.uid = one.uid;
      temp.date = one.date;
      temp.order_code = one.order_code;
      //找商品的信息
      for (let ware of wareList) {
        if (one.wareid == ware.id) {
          temp.wareName = ware.name;
          temp.image = ware.images[0];
          break;
        }
      }
      for (let vendor of vendorList) {
        if (one.vendorid == vendor.id) {
          temp.vendorName = vendor.name;
          break;
        }
      }
      //添加到返回数据中
      retData.push(temp);
    }
    return F.returnData(0, retOrder.msg, retData);
  }
};

/**
 @todo detail
 */
rp.detail = function*(fields) {

  let parameters = {};
  parameters.orderid = fields.orderid;


  //获取订单列表
  let retOrder = yield this.dao.getOneByQuery(parameters);
  if (retOrder.error == 1) return F.returnData(1, retOrder.msg, retOrder.data);

  let order = retOrder.data;

  //拼接返回的结果
  let retData = {};
  retData.wendorid = order.vendorid;
  retData.orderid = order.orderid;
  retData.wareid = order.wareid;
  retData.status = order.status;
  retData.has_consumed_number = order.has_consumed_number;
  retData.refunding_number = order.refunding_number;
  retData.has_refunded_number = order.has_refunded_number;
  retData.date = order.date;
  retData.quantity = order.quantity;
  retData.price = order.price;
  retData.totalPrice = order.total_price;
  retData.remarks = order.remarks || '';
  retData.pay_way = order.pay_way;
  retData.daily_thread_id = order.daily_thread_id;
  retData.consume_date = order.consume_date;
  retData.uid = order.uid;
  retData.pay_date = order.pay_date;
  retData.order_code = order.order_code;

  //找商品的信息 联表查询商店的信息
  let retWareDAta = {};
  if (fields.loc) {//传入用户的经纬度操作
    //let retWare = yield mongoWareDao.getOneByPopulate(order.wareid);
    //if (retWare.error == 1) return F.returnData(1, retWare.msg, retWare.data);


    let nearQue = {}
    nearQue.id = order.wareid;

    let arr = [];
    arr[0] = {
      '$geoNear': {
        'near': fields.loc || [],
        'spherical': true,
        'distanceField': 'dist',
        'includeLocs': 'loc',
        'query': nearQue
      }
    };
    let retAggre = yield mongoWareDao.getByAggregate(arr);
    if (retAggre.error == 1) return F.returnData(1, retAggre.msg, retAggre.data);
    let retWare = retAggre.data[0];


    //查询门店信息
    let shopIDs = [];
    for (let one of retWare.shops || []) shopIDs.push(one.sid);
    let retShop = yield F.getDataFromDispatcher('shop', 'getByIdArray', shopIDs)//根据商品中的shops的id集合,查询门店列表
    if (retShop.error == 1) return F.returnData(1, retShop.msg, retShop.data);
    //把门店的信息添加到商品的对于商店中
    let shops = [];
    for (let wareShop of retWare.shops || []) {
      for (let shop of retShop.data || []) {
        if (shop.id == wareShop.sid) wareShop.shopInfo = shop;
      }
      shops.push(wareShop);
    }
    retWare.shops = shops;
    retWareDAta = retWare;
  } else {//没有传入用户的经纬度,操作
    let retWare = yield mongoWareDao.getOneByPopulate(order.wareid);
    if (retWare.error == 1) return F.returnData(1, retWare.msg, retWare.data);
    retWareDAta = retWare.data;
  }


  retData.wareName = retWareDAta.name;
  retData.image = retWareDAta.images[0];
  retData.price = retWareDAta.price;
  if (retWareDAta.dist) retData.dist = retWareDAta.dist;
  if (retWareDAta.loc) retData.loc = retWareDAta.loc;


  //添加商家的电话详情
  retData.ShopInfo = [];
  for (let one of retWareDAta.shops) {
    let shop = {};
    one.shopInfo = one.shopInfo || {};
    shop.shopName = one.shopInfo.name || one.sName;
    shop.id = one.shopInfo.id || one.sid;
    if (fields.loc) shop.loc = one.shopInfo.loc || one.loc;
    if (one.shopInfo.tel) {
      shop.tel = one.shopInfo.tel || [];
    }
    retData.ShopInfo.push(shop);
  }


  //找商家的信息
  let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'getOneByQuery', {id: order.vendorid});

  if (retVendor.error == 1) return F.returnData(1, retVendor.msg, retVendor.data);
  retData.vendorName = retVendor.data.name;

  //获取用户信息
  let retUser = yield mysqlUserDao.findById(order.uid);
  if (retUser.error == 1) return F.returnData(1, retUser.msg, retUser.data);
  retData.mobile = retVendor.data.mobile;

  return F.returnData(0, retOrder.msg, retData);
};

/**
 * @todo 提供查询
 * @param fields 查询的对象
 * @returns {{error, msg, data}|{error, msg}}
 */
rp.findOneForDis = function*(fields) {
  let ret = yield  this.dao.getOneByQuery(fields);
  return F.returnData(0, ret.msg, ret.data);
};

/**
 @todo 查询
 */
rp.rawQuery = function *(sql) {
  let result = yield this.dao.rawQuery(sql);
  return result;
};

module.exports = OrderDispatcher;